#
# Una sezione in pratica il codice che viene servito da una pagina.
#

import os
import cgi
import datetime

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from Model import Nanny, Child, FBUser
from Utility import Utility
import logging
import facebook
from settings import FACEBOOK_APP_ID, FACEBOOK_APP_SECRET

#
# Main page 
#
class MainPage(webapp.RequestHandler):
    
    @property
    def currentFBUser(self):
        """
            user_birthday
            user_education_history
            user_hometown
            user_location
            user_work_history
            email
            scope=email,read_stream
        """
        if not hasattr(self, "_current_user"):
            self._current_user = None
            cookie = facebook.get_user_from_cookie(
                self.request.cookies, FACEBOOK_APP_ID, FACEBOOK_APP_SECRET)
            if cookie:
                # Store a local instance of the user data so we don't need
                # a round-trip to Facebook on every request
                user = FBUser.get_by_key_name(cookie["uid"])
                if not user:
                    graph = facebook.GraphAPI(cookie["access_token"])
                    profile = graph.get_object("me")
                    user =FBUser(key_name=str(profile["id"]),
                                fbid=str(profile["id"]),
                                name=profile["name"],
                                profile_url=profile["link"],
                                access_token=cookie["access_token"])
                    user.put()
                elif user.access_token != cookie["access_token"]:
                    user.access_token = cookie["access_token"]
                    user.put()
                self._current_user = user
        return self._current_user

  
    def getTemplateValues(self, *arg, **dic):
        
        #user = users.get_current_user()
        user = self.currentFBUser
        template_values = dict()
        if user :
        #    template_values['redirectUrl'] = users.create_logout_url("/" )
            template_values['signed'] = True
            template_values['userNick'] = user.name
        else:
        #   template_values['redirectUrl'] = users.create_login_url("/")
            template_values['signed'] = False
        
        template_values['current_user'] = self.currentFBUser
        template_values['facebook_app_id'] = FACEBOOK_APP_ID            
            
        return template_values
        
    def getTemplate(self, *arg, **dic):
        return 'index.html'
    
    def renderTemplate(self, template_values ):
        template_path = Utility.getTemplatePath(self.getTemplate())        
        self.response.out.write(template.render(template_path, template_values))
           
    def get(self):
        NannyCount = Nanny.all().count()
        ChildCount = Child.all().count()
    
        template_values = self.getTemplateValues()
        template_values['NannyCount'] = NannyCount
        template_values['ChildCount'] = ChildCount
    
        self.renderTemplate(template_values)
    


class ThankYou( MainPage ):
    
    def getTemplate(self, *arg, **dic):
        return 'thankyou.html'
    
    def getTemplateValues(self, *arg, **dic):
        cgi = self.request
        nanny = Nanny.get_by_id(int(cgi.get('nanny_id')) )
        return {} if nanny is None else {'FirstName': nanny.FirstName,'LastName' : nanny.LastName }
        
    def get(self):
        template_values = self.getTemplateValue( )
        if len(template_values) == 0 :
            logging.info("Thank you page has found no Nanny")
            return self.redirect('/')
            
        self.renderTemplate(template_values)
        
        
    def post(self):
        pass



class Sign( MainPage ):
    
  def post(self):
      
    nanny = Nanny()

    cgi = self.request
    nanny.email                       = db.Email(cgi.get('Email')) 
    nanny.FirstName                   = db.Text(cgi.get('FirstName'))
    nanny.LastName                    = db.Text(cgi.get('LastName'))
    nanny.Gender                      = True if cgi.get('Gender') == 'Female' else False 
    #nanny.BirthDate                   = db.DateTime(cgi.get('BirthDate'))
    nanny.PostalAddress               = db.PostalAddress(cgi.get('PostalAddress'))
    nanny.PrimayPhone                 = db.PhoneNumber(cgi.get('PrimaryPhone'))
    if cgi.get('SecondaryPhone'):
        nanny.SecondaryPhone              = db.PhoneNumber(cgi.get('SecondaryPhone') )
    nanny.AllowUserToSeePhone         = True if cgi.get('AllowUserToSeePhone') == 'Yes' else  False
    nanny.Nationality                 = db.Text(cgi.get('Nationality'))
    nanny.HaveChildren                = True if cgi.get('HaveChildren') == 'Yes' else False
    if cgi.get('ChildrenAccompaignAges') :
        nanny.ChildrenAccompaignAges      = db.Text(cgi.get('ChildrenAccompaignAges')  )


    nanny.put()
    key = nanny.key()
    nanny.send_welcome_mail()
    self.redirect('/thankyou/?nanny_id=%s' % key.id() )



class Call( MainPage ):
    def getTemplate(self):
        return 'call.html'
    
class File( MainPage ):
    def getTemplate(self):
        return 'file.html'
    
class Forum( MainPage ):
    def getTemplate(self):
        return 'forum.html'

class OnWire( webapp.RequestHandler):
    def getTemplate(self):
        return 'onWire.html'
        

class Photo( webapp.RequestHandler):
    def getTemplate(self):
        return 'photo.html'
    
class Recipe( webapp.RequestHandler):
    def getTemplate(self):
        return 'recipe.html'
    
class Toy( MainPage ):
    def getTemplate(self):
        return 'toy.html'

        
class Manager( MainPage ):
    def getTemplate(self):
        return 'manager.html'    
    
    